#include "receiver.h"

network::receiver::~receiver()
{ }

void network::receiver::run()
{
	while(1) {
		if(is_interrupted()) {
			return;
		}
		try {
			string tmp = _sock->recv();
			boost::shared_ptr<model::dom> ptr(_pars->parse(tmp));

			boost::shared_ptr<network::message> msg(
				new network::message);
			msg->sock = _sock;
			msg->node = ptr;
			msg->type = network::RECEIVE;

			_queue->put(msg);
		} catch(const network::parse_exception &e) {
		} catch(const network::lost_connection_exception &e) {
			boost::shared_ptr<network::receiver> ptr(_this.lock());
			send_delete();
			_this.reset();
			return;
		} catch(const network::socket_exception &e) {
			boost::shared_ptr<network::receiver> ptr(_this.lock());
			send_delete();
			_this.reset();
			return;
		} catch(...) {
			cout << "strange exception" << endl;
			return;
		}
	}
}

void network::receiver::send_delete()
{
	fire_listener();

	boost::shared_ptr<network::message> msg(
		new network::message);
	msg->sock = _sock;
	msg->node = boost::shared_ptr<model::dom>();
	msg->type = network::DELETE;
	_queue->put(msg);
}

